<?php

namespace app\queue\stomp;

use app\queue\BaseConsumer;
use support\bootstrap\Redis;
use Webman\Stomp\RetryAbleConsumer;
use malkusch\lock\mutex\PHPRedisMutex;
use common\service\OrderTaskFileListService;

/**
 * 检查版本是否需要发送给乙方
 */
class VersionOrderTaskUpstreamCheckConsumer extends BaseConsumer implements RetryAbleConsumer
{

    // 要消费的队列名
    public $queue = 'version_order_task_upstream_check';

    // 连接名，对应 config/redis_queue.php 里的连接`
    public $connection = 'default';

    /**
     * 任务排期
     * @param $data
     * @return void
     * @throws \Exception
     */
    public function doConsume($data)
    {
        $checkKey = $this->queue . ':' . $data['version_id'];
        $mutex = new PHPRedisMutex([Redis::connection()->client()], $checkKey, $this->getTtr());
        return $mutex->synchronized(function () use ($data) {
            OrderTaskFileListService::getInstance()->versionOrderTaskUpstreamCheck($data['version_id']);
        });
    }

    /**
     * 重试间隔
     * @return int
     */
    public function getTtr()
    {
        return 60;
    }

    /**
     * 能否重试
     * @param $attempt
     * @param $error
     * @return bool
     */
    public function canRetry($attempt, $error)
    {
        trace(format_exception_info($error), 'ERR');
        return $attempt <= 5;
    }
}
